package com.bjb.vr.remote.ws.rabbitmq.handler.impl;

import com.alibaba.fastjson.JSONObject;
import com.bjb.vr.common.service.ResDeviceService;
import com.bjb.vr.common.utils.RedisUtil;
import com.bjb.vr.remote.ws.rabbitmq.constants.MessageActionConstants;
import com.bjb.vr.remote.ws.rabbitmq.entity.RabbitWebSocketMsg;
import com.bjb.vr.remote.ws.rabbitmq.handler.MessageHandler;
import com.bjb.vr.remote.ws.redis.constants.RedisConstants;
import com.bjb.vr.remote.ws.websocket.vo.Message;
import com.bjb.vr.remote.ws.websocket.websocket.WebSocketMsgHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @version 1.0.0
 * @description:
 * @author: caihaibo
 * @createDate: 2022/3/29
 */
@Component
@Slf4j
public class CvrUpdateBundleStateMessageHandler implements MessageHandler {

    @Autowired
    ResDeviceService resDeviceService;

    @Autowired
    RedisUtil redisUtil;

    final String  LOCK_KEY = "res_device_bundle";

    @Override
    public void process(RabbitWebSocketMsg rabbitWebSocketMsg) {
        String dbLockKey = RedisConstants.WEBSOCKET_DB_OP_LOCK_KEY + LOCK_KEY+ rabbitWebSocketMsg.getDeviceId();

        JSONObject jsonObject = JSONObject.parseObject(rabbitWebSocketMsg.getMsg());

        Message message = JSONObject.toJavaObject(jsonObject, Message.class);

        if(message.getAction().equals(MessageActionConstants.MESSAGE_ACTION_CVR_UPDATE_BUNDLE_STATE)){
            log.info("处理头盔上传更新课程状态信息");
            WebSocketMsgHandler.sendAdmin(rabbitWebSocketMsg);
            JSONObject _jsonObject = JSONObject.parseObject(message.getCommand().getParameter());
            int updateBundleState = _jsonObject.getInteger("updateBundleState");
            long resBundleId = _jsonObject.getLong("resBundleId");
            String updateBundleMsg = _jsonObject.getString("updateBundleMsg");
            String udid = message.getCommand().getUdid();
            String value = String.valueOf(System.currentTimeMillis());
            if(redisUtil.lock(dbLockKey,value,RedisConstants.WEBSOCKET_DB_OP_LOCK_KEY_EXPIRE_TIME)) {
                resDeviceService.updateResDeviceUpdateBundleStateByUdid(udid, resBundleId, updateBundleState, updateBundleMsg);
                redisUtil.unlock(dbLockKey, value);
            }
        }
    }
}
